package cn.cxy.demo

import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        writeDataBtn.setOnClickListener { writeSharedPreference() }
        readDataBtn.setOnClickListener { readSharedPreference() }
    }

    /**
     * 向SharedPreference中写入数据
     */
    private fun writeSharedPreference() {
        val spFileName = "test_sp_file"
        val editor = getSharedPreferences(spFileName, Context.MODE_PRIVATE).edit()
        editor.putString("userName", "萝莉")
        editor.putInt("age", 16)
        editor.putBoolean("isBeauty", true)
        editor.apply()
    }

    /**
     * 从SharedPreference中读取数据
     */
    private fun readSharedPreference() {
        val spFileName = "test_sp_file"
        val sp = getSharedPreferences(spFileName, Context.MODE_PRIVATE)
        val name = sp.getString("userName", "")
        val age = sp.getInt("age", 0)
        val isBeauty = sp.getBoolean("isBeauty", true)
        Log.d("MainActivity", "姓名：$name")
        Log.d("MainActivity", "年龄：$age")
        Log.d("MainActivity", "是否漂亮：$isBeauty")
    }
}